package net.osweb.core.tools.utils.crm;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import net.osweb.core.tools.utils.ftp.FileConfig;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 * @author hgg
 * 加载FTP配置文件
 */
public class InitFileConfig implements InitializingBean {
	protected final Log logger = LogFactory.getLog(getClass());
	private Resource fileConf;

	public void afterPropertiesSet() throws Exception {
		logger.info("----------------------  InitFileConfig  begin   ------------------------------");
		File file = fileConf.getFile();

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(file);
		NodeList nl = doc.getElementsByTagName("server");
		for (int i = 0; i < nl.getLength(); i++) {
			String name = doc.getElementsByTagName("name").item(i)
					.getFirstChild().getNodeValue();
			String ip = doc.getElementsByTagName("ip").item(i).getFirstChild()
					.getNodeValue();
			String httpPath = doc.getElementsByTagName("http-path").item(i)
					.getFirstChild().getNodeValue();
			String httpPort = doc.getElementsByTagName("http-port").item(i)
					.getFirstChild().getNodeValue();
			String ftpPath = doc.getElementsByTagName("ftp-path").item(i)
					.getFirstChild().getNodeValue();
			String ftpPort = doc.getElementsByTagName("ftp-port").item(i)
					.getFirstChild().getNodeValue();
			String ftpUser = doc.getElementsByTagName("ftp-user").item(i)
					.getFirstChild().getNodeValue();
			String ftpPassword = doc.getElementsByTagName("ftp-password").item(
					i).getFirstChild().getNodeValue();

			FileConfig fileConfig = FileConfig.getInstance();
			fileConfig.setFtpPassword(ftpPassword);
			fileConfig.setFtpPath(ftpPath);
			fileConfig.setFtpPort(ftpPort);
			fileConfig.setFtpUser(ftpUser);
			fileConfig.setHttpPath(httpPath);
			fileConfig.setName(name);
			fileConfig.setIp(ip);
			fileConfig.setHttpPort(httpPort);
			
			logger.info("----------------------  InitFileConfig  end   ------------------------------");
		}
	}

	public Resource getFileConf() {
		return fileConf;
	}

	public void setFileConf(Resource fileConf) {
		this.fileConf = fileConf;
	}

	
	
}
